package com.ityun.ogapp.wechat

import android.content.ComponentName
import android.content.Intent
import android.view.accessibility.AccessibilityNodeInfo
import com.blankj.utilcode.util.ToastUtils
import com.ven.assists.AssistsCore
import com.ven.assists.service.AssistsService
import com.ven.assists.simple.step.StepTag
import com.ven.assists.stepper.Step
import com.ven.assists.stepper.StepCollector
import com.ven.assists.stepper.StepImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

class WechatVideoManager : StepImpl() {

    private var number = 0
    override fun onImpl(collector: StepCollector) {
        collector.next(StepTag.STEP_1) {
            // 启动微信到首页
            Intent().apply {
                addCategory(Intent.CATEGORY_LAUNCHER)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                component = ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI")
                AssistsService.instance?.startActivity(this)
            }
            number = 0
            // 直接跳转到查找步骤，跳过通讯录
            return@next Step.get(StepTag.STEP_2, data = it.data, delay = 500)
        }.next(StepTag.STEP_2) {
            // 查找对应的用户
            val infos =
                AssistsCore.findById("com.tencent.mm:id/kbq", filterText = it.data as String)
            if (infos.isNotEmpty()) {
                var clicked = false
                infos.forEach { it1 ->
                    var parent: AccessibilityNodeInfo? = it1.parent
                    while (parent != null) {
                        if (parent.isClickable) {
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            parent.recycle()
                            clicked = true
                            break
                        }
                        val tempParent = parent.parent
                        parent.recycle()
                        parent = tempParent
                    }
                }
                if (clicked) {
                    delay(1000) // 等待聊天界面加载
                    return@next Step.get(StepTag.STEP_3)
                } else {
                    // 在协程作用域内
                    withContext(Dispatchers.Main) {
                        ToastUtils.showLong("未找到联系人")
                    }
                    return@next Step.repeat
                }
            } else {
                withContext(Dispatchers.Main) {
                    ToastUtils.showLong("未找到联系人")
                }
                return@next Step.repeat
            }
        }
    }
}